<script setup lang='ts'>
import type { TableColumnCtx } from 'element-plus'

import { useGetMaterialsList, useGetPricTree, useSaveBatch } from '@fl/api/man-api/pricing-tool'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { ElTree } from 'element-plus'
import { cloneDeep, isNull } from 'lodash-es'
import NP from 'number-precision'

import addModel from './add-model.vue'

type Tree = {
    [key: string]: any
}
const { query } = useRoute()
const treeRef = ref<InstanceType<typeof ElTree>>()
const filterText = ref('')
const router = useRouter()
const visible = ref<boolean>(false)
const currentItemId = ref<string>('')
const currentCategoryId = ref<string>('')
const records = ref<any>([])
const modelIdList = ref<any>([])
const { createMessage } = useMessage()
const params = computed(() => ({
    categoryId: query?.categoryId || '',
}))
const { data: list, isLoading: isTreeLoading } = useGetPricTree(params)
const treeData = computed(() => {
    return list.value ? [list.value] : []
})

const categoryId = ref<string>('')

const materialsParams = computed(() => ({
    categoryId: categoryId.value,
    projectId: query?.id || '',
}))

const { data: tableData, isLoading, refetch } = useGetMaterialsList(materialsParams)
const { isPending, mutate: saveMutate } = useSaveBatch()

watchEffect(() => {
    if (tableData.value) {
        records.value = cloneDeep(tableData.value)
    }
})

const defaultProps = {
    children: 'children',
    label: 'categoryName',
}

type Model = {
    categoryId?: number | string
    flag?: number
    itemId?: number | string
    itemName?: string
    modelId?: number | string
    modelName?: string
    price?: number | string
    projectId?: number | string
    unit?: string
}

type SpanMethodProps = {
    column?: TableColumnCtx<Model>
    columnIndex?: number
    row?: Model
    rowIndex: number
}

const receordSpans = computed(() => {
    // 返回对象
    const arr: any = {} // {index: {id: itemId, value: [相同id的个数]}}
    let currIndex
    for (let i = 0; i < records.value.length; i++) {
        const record = records.value[i]
        const { itemId: id } = record
        if (arr[currIndex]?.id === id) {
            arr[currIndex].value++
        }
        else {
            arr[i] = { id, value: 1 }
            currIndex = i
        }
    }
    return arr
})

function checkModelSize(itemId) {
    return records.value.filter((item: any) => item.itemId === itemId).length
}

function objectSpanMethod({ columnIndex, rowIndex }: SpanMethodProps) {
    if (columnIndex !== 0)
        return
    const spanData = receordSpans.value[rowIndex]

    if (!spanData) {
        return {
            colspan: 0,
            rowspan: 0,
        }
    }
    return {
        colspan: 1,
        rowspan: spanData.value,
    }
}

function truncateToFourDecimals(num: number) {
    const parts = num.toString().split('.')
    if (parts.length === 2 && parts[1].length > 4) {
        parts[1] = parts[1].substring(0, 4)
        return `${parts[0]}.${parts[1]}`
    }
    return num
};

function filterNode(value: string, data: Tree) {
    if (!value)
        return true
    return data.categoryName.includes(value)
}

function handleNodeClick(data: any) {
    categoryId.value = data.id
    refetch()
}

function delList(itemId: string, modelId: string) {
    if (checkModelSize(itemId) === 1) {
        createMessage.warning('至少保存一条规格型号数据')
        return
    }
    records.value = records.value?.filter((item: any) => item.modelId !== modelId)
    createMessage.success('删除成功')
}

function addModelHandle(itemId, categoryId) {
    modelIdList.value = records.value.filter((item: any) => item.itemId === itemId).map((item: any) => item.modelId)
    currentItemId.value = itemId
    currentCategoryId.value = categoryId
    visible.value = true
}

function save() {
    const flag = records.value.some((item: any) => {
        return item.price === null
    })

    if (flag) {
        createMessage.warning('请完善未填写的除税单价')
        return
    }
    const params = records.value.map((item: any) => {
        return {
            ...item,
            projectId: query?.id,
        }
    })

    console.log('params', flag, params)
    saveMutate(params, {
        onSuccess: () => {
            ElMessage.success('保存成功')
        },
    })
}

function cancel() {
    router.back()
}

function addNewItemsByItemId(itemId, newItems, data) {
    let lastIndex = -1
    for (let i = 0; i < data.length; i++) {
        if (data[i].itemId === itemId) {
            lastIndex = i
        }
    }

    if (lastIndex !== -1) {
        data.splice(lastIndex + 1, 0, ...newItems)
    }
    else {
        console.log(`没有找到 itemId 为 ${itemId} 的数据`)
    }
}

function handleSave(data: any) {
    addNewItemsByItemId(data.itemId, data?.result, records.value)
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})
</script>

<template>
    <div class="category-wrap">
        <div class="left">
            <div class="tree-wrap">
                <el-input v-model="filterText"
                          class="mx-20 mt-20"
                          style="width: 240px"
                          placeholder="请输入"
                />

                <ElTree ref="treeRef"
                        v-load="isTreeLoading"
                        :data="treeData"
                        class="py-10 pl-10 pr-15"
                        node-key="id"
                        highlight-current
                        default-expand-all
                        :props="defaultProps"
                        :filter-node-method="filterNode"
                        :expand-on-click-node="false"
                        @node-click="handleNodeClick"
                />
            </div>
        </div>

        <div class="right">
            <el-button type="default"
                       class="mb-20"
                       @click="cancel"
            >
                返回列表
            </el-button>

            <ElCard shadow="never"
                    class="h-full"
            >
                <div class="flex w-full justify-between items-center">
                    <div class="text-20 text-[#1D2129] font-bold">
                        编辑报价清单
                    </div>

                    <!-- <div>
                        <el-button type="primary"
                                   @click="cancel"
                        >
                            复制报价清单
                        </el-button>

                        <el-button type="primary"
                                   @click="cancel"
                        >
                            粘贴报价清单
                        </el-button>
                    </div> -->
                </div>

                <el-table v-loading="isLoading"
                          height="530"
                          :data="records"
                          :span-method="objectSpanMethod"
                          border
                          style="width: 100%; margin-top: 20px"
                >
                    <el-table-column prop="itemName"
                                     label="材料名称"
                                     width="180"
                    >
                        <template #default="{ row }">
                            {{ row.itemName }} <span v-if="row.flag === 1"
                                                     class="ml-20 text-[#DA0004] cursor-pointer"
                                                     @click="addModelHandle(row.itemId, row.categoryId)"
                            >添加型号</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="model"
                                     align="center"
                                     label="规格型号"
                    />

                    <el-table-column prop="price"
                                     align="center"
                                     label="除税单价(元)"
                    >
                        <template #default="{ row }">
                            <el-input-number v-model="row.price"
                                             :step="0.0001"
                                             placeholder="请输入"
                                             :min="0"
                                             :max="999999"
                                             controls-position="right"
                                             @blur="() => {
                                                 row.price = isNull(row.price) ? row.price : parseFloat(NP.strip(truncateToFourDecimals(row.price)))
                                             }"
                            />
                        </template>
                    </el-table-column>

                    <el-table-column prop="unit"
                                     align="center"
                                     label="单位"
                    />

                    <el-table-column align="center"
                                     label="操作"
                    >
                        <template #default="{ row }">
                            <el-space>
                                <div class="text-[#DA0004]">
                                    <span v-if="row.flag === 1"
                                          class="cursor-pointer"
                                          @click="delList(row.itemId, row.modelId)"
                                    >
                                        删除
                                    </span>
                                </div>
                            </el-space>
                        </template>
                    </el-table-column>
                </el-table>

                <div v-if="records.length > 0"
                     class="pt-50 flex w-full justify-center"
                >
                    <SubmitBtn type="primary"
                               :loading="isPending"
                               @click="save"
                    >
                        保存
                    </SubmitBtn>

                    <el-button @click="cancel">
                        取消
                    </el-button>
                </div>
            </ElCard>
        </div>
    </div>

    <addModel v-model:visible="visible"
              :current-category-id="currentCategoryId"
              :current-item-id="currentItemId"
              :model-id-list="modelIdList"
              :project-id="query.id"
              @save="handleSave"
    />
</template>

<style scoped lang='less'>
.category-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    overflow: hidden;

    .left {
        width: max-content;
        min-width: 288px;
        margin-right: 10px;
        background-color: #fff;
        overflow: hidden;
        .tree-wrap {
            width: 100%;
            height: 720px;
            overflow-y: auto;
        }
    }

    .right {
        flex: 1;
        // background-color: #fff;
        overflow: hidden;
    }
}
</style>
